<template>
    <div class="view" :data-mag="socketMsg">
        <android-nav-bar style="background: #f0f0f2;border-bottom: none" title="情感专家" v-on:back="back"></android-nav-bar>
        <div class="expert-wrap">
            <cube-scroll :data="expertList" @pulling-down="onPullingDown" :options="options">
                <div class="expert-context">
                    <div class="expert-item" :class="{'expert-online':!!expert.isOnline}" @click="toChatPage(expert.user_id)" v-for="expert in expertList" :key="expert.user_id">
                        <div class="expert-face" :style="`background-image: url(${expert.avatar.file_path}?imageView2/0/w/70);`"></div>
                        <div class="expert-name">
                            {{expert.nickName}}
                        </div>
                        <template v-if="expert.lastMessage">
                            <div class="expert-message ellipsis-2">
                                {{expert.lastMessage.content | msgAbbreviation}}
                            </div>
                            <div class="expert-time">
                                {{expert.lastMessage.time | timeStamp | dateDiff}}
                            </div>
                        </template>
                        <div class="expert-online">{{!!expert.isOnline?'在线':'离线'}}</div>
                        <div class="expert-chat">{{!!expert.chatStatus?'正在咨询':''}}</div>
                    </div>
                </div>
            </cube-scroll>
            <div class="expert-bottom">
                <div class="current-frequency">可咨询：<span>{{user.consultationNum}}</span>次</div>
                <div class="buy-frequency" @click="showBuyPicker=true">购买</div>
            </div>
        </div>
        <div class="buy-picker" v-show="showBuyPicker">
            <div class="buy-picker-content">
                <div class="buy-picker-content-close" @click="showBuyPicker=false">
                    <i class="cubeic-close"></i>
                </div>
                <!--                <div class="buy-picker-content-background"></div>-->
                <div class="buy-picker-content-title">购买咨询次数</div>
                <div class="buy-picker-content-list">
                    <div class="buy-picker-content-cell" :class="{'buy-picker-content-cell-selected':index === consultSelecedtIndex}" v-for="(consultItem,index) in consultItemList" :key="index" @click="selectConsult(index)">
                        <div class="buy-picker-content-name ellipsis-2">{{consultItem.name}}</div>
                        <div class="buy-picker-content-number">可咨询<span>{{consultItem.consultation_num}}</span>次</div>
                        <div class="buy-picker-content-money">{{consultItem.price}}</div>
                    </div>

                </div>
                <div class="buy-picker-content-btn" @click="buyFrequency">
                    立即购买
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";
    import Badge from "@/components/aui/Badge.vue";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import DialogConfig from "@/constant/DialogConfig";
    import {InterfaceSocket} from "@/interface/InterfaceSocket";
    import AndroidNavBar from "../components/aui/AndroidNavBar.vue";
    import {updateDataCache} from "@/store/dispatches";
    // import Recorder from 'js-audio-recorder';

    @Component({
        components: {
            Badge, AndroidNavBar
        },
    })
    export default class ExpertList extends Scene {
        private showBuyPicker: boolean = false;
        private expertList: any[] = [];
        private isLoaded: boolean = false;
        private frequency: number = 0;
        private consultItemList: any[] = [];
        private consultSelecedtIndex = 2;

        @State("UserStore")
        public user!: InterfaceUser;

        @State("SocketStore")
        private socket!: InterfaceSocket;

        @State("DataCacheStore")
        public dataCache!: any;

        private get socketMsg(): any {
            if (this.socket.message.type === "expert_layout" || this.socket.message.type === "expert_login" || this.socket.message.type === "finish") {
                this.$nextTick(() => {
                    this.getExpertList();
                    this.getConsultItemList();
                });
            }

            return JSON.stringify(this.socket.message);
        }

        private get options(): any {
            return {
                pullDownRefresh: {
                    threshold: 60,
                    stop: 40,
                    txt: "更新成功"
                },
                pullUpLoad: false
            };
        }

        private back() {
            this.navigateBack();
        }

        private onPullingDown() {
            setTimeout(() => {
                this.getExpertList();
            }, 500);
        }

        private mounted() {
            this.expertList = this.dataCache.expertList;
            this.$nextTick(() => {
                this.getExpertList();
                this.getConsultItemList();
            });
        }


        private getExpertList(): void {
            Http.get(this.api.getExpertList, {}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    this.isLoaded = true;
                    setTimeout(() => {
                        this.expertList = res.data;
                        updateDataCache({expertList: res.data});
                    }, 500);
                } else {
                    this.globalSingleResultToast(res);
                }


            });
        }

        private async toChatPage(id: number): Promise<any> {
            let toast = (<any> this).$createToast({
                time: 0,
                txt: "正在与专家建立会话",
                mask: true
            }).show();
            try {
                const res = await Http.post(this.api.confirmExpertConsulation, {user_id: id}, {token: this.user.token});
                if (res.code === 1) {
                    if (!this.socket.isConnected) {
                        (<any> this).$disconnect();
                        try {
                            (<any> this).$connect();
                        } catch (e) {
                        }
                    }
                    toast = (<any> this).$createToast({
                        time: 1000,
                        correct: "correct",
                        txt: "会话建立成功，即将开始咨询",
                        mask: true,
                        onTimeout: () => {
                            this.navigateTo({
                                name: "chatDetail",
                                query: {
                                    type: 3,
                                    toId: id
                                }
                            });
                        }
                    }).show();
                } else {
                    if (res.data.status === 100) {
                        toast.hide();
                        this.navigateTo({
                            name: "chatDetail",
                            query: {
                                type: 3,
                                toId: id
                            }
                        });
                    } else {
                        if (this.globalSingleResultToast(res)) {
                            setTimeout(() => {
                                this.showBuyPicker = true;
                            }, 2500);
                        }
                    }
                }
            } catch (e) {
                toast = (<any> this).$createToast({
                    time: 1000,
                    type: "error",
                    txt: "会话建立失败，本次会话不产生任何费用",
                    mask: true
                }).show();
            }

        }

        private async buyFrequency(): Promise<any> {
            let toast = (<any> this).$createToast({
                time: 0,
                txt: "正在生成订单",
                mask: true
            }).show();
            try {
                const res = await Http.post(this.api.placeExpertOrder, {id: this.consultItemList[this.consultSelecedtIndex].id}, {token: this.user.token});
                if (res.code === 1) {
                    toast.hide();
                    this.showBuyPicker = false;
                    this.redirectTo({
                        name: "orderChannel",
                        query: {
                            orderIds: res.data.id.join(","),
                            orderType: "expert"
                        }

                    });
                } else {
                    this.globalSingleResultToast(res);
                }
            } catch (e) {
                toast = (<any> this).$createToast({
                    time: 1000,
                    type: "error",
                    txt: "会话建立失败，本次会话不产生任何费用",
                    mask: true
                }).show();
            }
        }

        private getConsultItemList() {
            Http.get(this.api.getConsultItemList).then((res) => {
                if (res.code === 1) {
                    this.consultItemList.splice(0, this.consultItemList.length);
                    this.consultItemList.push(...res.data);
                }
            });
        }

        private selectConsult(i: number) {
            this.consultSelecedtIndex = i;
        }

    }
</script>

<style scoped lang="stylus">
    .view
        width 100vw;
        height 100vh
        background #f0f0f2;
        overflow hidden

        .expert-wrap
            width 100vw;
            background #f0f0f2
            margin-top calc(var(--safe-area-inset-top) + 47px);
            height calc(100vh - var(--safe-area-inset-top) - 47px);
            position relative;

            .expert-context
                padding 15px 15px calc(50px + var(--safe-area-inset-bottom)) 15px;
                display flex;
                flex-wrap wrap;
                justify-content space-between;

                .expert-item
                    background #fff;
                    height 190px;
                    width 165px;
                    margin-bottom 15px;
                    border-radius 13px;
                    border 1px solid #e9eaee
                    padding 15px;
                    position relative;
                    display block;
                    filter grayscale(100%);

                    &.expert-online
                        filter none


                    .expert-face
                        width 57px;
                        height 57px;
                        background-position center;
                        background-size cover;
                        border-radius 100%;

                    .expert-name
                        padding 2px 0
                        margin 3px 0 2px 0;
                        font-size 15px;
                        color #2c2f36;
                        line-height 20px;

                    .expert-message
                        width 100%
                        font-size 12px;
                        line-height 20px;
                        word-wrap break-word;

                    .expert-time
                        position absolute;
                        left 12px;
                        bottom 15px;
                        color #ccc;
                        font-size 12px;

                    .expert-chat
                        position absolute;
                        bottom 15px;
                        right 15px;
                        font-size 12px;
                        color #999;

                    .expert-online
                        position absolute;
                        top 15px;
                        right 15px;
                        font-size 12px;
                        color #333;
                        display flex;
                        justify-content center;
                        align-items center;

                        &::before
                            content '';
                            width 6px;
                            height 6px;
                            display block;
                            background $theme-common-color;
                            margin-right 3px;
                            border-radius 6px;


        .expert-bottom
            height calc(45px + var(--safe-area-inset-bottom));
            background $theme-thin-color
            position absolute;
            bottom 0;
            width 100vw;
            display flex;
            align-items center;
            justify-content space-between;
            padding 0 12px var(--safe-area-inset-bottom) 12px;
            z-index 10;

            .current-frequency
                font-size 13px;
                color #666;

                span
                    font-size 16px;
                    color #333;
                    padding-right 4px;

            .buy-frequency
                width 60px;
                height 30px;
                line-height 30px;
                text-align center;
                background $theme-common-color;
                color #fff;
                font-size 12px;
                border-radius 3px;

        .buy-picker
            position absolute;
            height 100vh;
            width 100vw;
            background rgba(0, 0, 0, .3);
            top 0;
            left 0;
            z-index 101;
            display flex;
            justify-content center;
            align-items center;

            .buy-picker-content
                width 80vw;
                padding 10px 12px;
                background #fff;
                border-radius 7px;
                box-shadow: 0 .5px 10px rgba(0, 0, 0, 0.21)
                display flex;
                justify-content center;
                align-items center;
                flex-direction column;
                position relative;
                overflow hidden

                .buy-picker-content-close
                    position absolute;
                    top 12px;
                    right 12px;
                    display flex;
                    justify-content center;
                    align-items center;

                .buy-picker-content-background
                    background-image: url('/assets/images/background-expert.jpeg')
                    background-position center;
                    background-size cover;
                    position absolute;
                    opacity .2
                    width 100%;
                    height 100%;
                    filter blur(2px);

                .buy-picker-content-title
                    display flex;
                    justify-content center;
                    align-items center;
                    height 35px;
                    color $theme-common-color;
                    font-size 15px;

                .buy-picker-content-list
                    margin-top 15px;
                    width 100%;
                    display flex;
                    justify-content space-between;

                    .buy-picker-content-cell-selected
                        border 1px solid $theme-common-color !important;

                    .buy-picker-content-cell
                        width calc((100% - 20px) / 3);
                        height 100px;
                        border 1px solid $theme-thin-color;
                        border-radius 5px;
                        display flex;
                        flex-direction column;
                        justify-content space-between;
                        color $theme-common-color;


                        .buy-picker-content-name
                            font-size 14px;
                            padding 7px 5px;
                            line-height 1.5
                            display flex;
                            justify-content center
                            align-items center;
                            text-align center;

                        .buy-picker-content-number
                            height 20px;
                            font-size 12px;
                            display flex;
                            justify-content center;
                            align-items flex-end;

                            span
                                font-size 15px;
                                padding 0 3px;

                        .buy-picker-content-money
                            display flex;
                            justify-content center;
                            align-items flex-end;
                            font-size 16px;
                            padding-bottom 7px;
                            height 30px;

                            &::before
                                content '¥';
                                padding-bottom 3px;
                                padding-left 2px;
                                font-size 11px;


                .buy-picker-content-btn
                    height 40px;
                    border-radius 7px;
                    background $theme-common-color;
                    display flex;
                    width 100%;
                    justify-content center;
                    align-items center;
                    margin-top 20px;
                    color #fff;
                    padding-bottom var(--safe-area-inset-bottom);

</style>
